//
//  YSPStatus.swift
//  Weibo Demo
//
//  Created by 朴裕识 on 15/12/20.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SDWebImage

class YSPStatus: NSObject {
    ///模型的属性
    /// 创建时间
    var created_at: String?
    
    /// 微博id
    var id: Int = 0
    
    /// 微博正文内容
    var text: String?
    
    /// 来源
    var source: String?
    
    /// 微博的配图 [String: AnyObject]
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            let count  = pic_urls?.count ?? 0
            if count == 0 {
                //没有配图
                return
            }
            picURLArray = [NSURL]()
            for dic in pic_urls! {
                let URLString = dic["thumbnail_pic"] as! String
                let URL = NSURL(string: URLString)
                picURLArray?.append(URL!)
            }
        }
    }
    
    
    /// 微博配图的URL数组
    var picURLArray: [NSURL]?
    
    /// 根据不同微博类型返回不同配图数组
    var realPicURLArray: [NSURL]? {
        get {
            return retweeted_status == nil ? picURLArray : retweeted_status?.picURLArray
        }
    }
    
    /// 转发数
    var reposts_count: Int = 0
    
    /// 评论数
    var comments_count: Int = 0
    
    /// 表态数(赞)
    var attitudes_count: Int = 0
    
    /// 用户信息
    var userInfoArray: YSPUser?
    
    /// 行高
    var rowHeight: CGFloat?
    
    ///转发微博模型
    var retweeted_status: YSPStatus?
    
    func getCellType() -> String {
        return retweeted_status == nil ? ReuseIdentifier.OriginalCellReuseIdentifier.rawValue : ReuseIdentifier.ForwardCellReuseIdentifier.rawValue
    }
    
    //字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    //在这里截取user的转模型过程
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                let userModel = YSPUser(dict: dict)
                userInfoArray = userModel
            }
            return
        }
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = YSPStatus(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    override var description: String {
        let prop = ["created_at", "id", "text", "source", "pic_urls", "reposts_count", "comments_count", "attitudes_count"]
        
        // 通过一个数组来生成一个字典,数组中的元素,会成为字典的key,key所对应的value，会从模型中来找对应的属性值
        let dict = dictionaryWithValuesForKeys(prop)
        return "\n\t微博模型: \(dict)"
    }
    
    //MARK: - 加载微博数据
    class func loadStatus(since_id: Int, max_id: Int, finished: (statusArray: [YSPStatus]?, error: NSError?) -> ()) {
        YSPNetworkTool.sharedNetworkTool.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil || result == nil {
                finished(statusArray: nil, error: error)
                return
            }
            
            //来到这里说明有数据
            //判断数据里有没有statuses数组，有的话转成数组，里面装的是字典
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                //能来到这里说明有statuses数组
                //创建模型数组
                var modelArray = [YSPStatus]()
                for dict in array {
                    let status = YSPStatus.init(dict: dict)
                    modelArray.append(status)
                }
                //缓存图片
                cacheImage(modelArray, finished: finished)
                //告诉调用者有模型了
                //                finished(statusArray: modelArray, error: nil)
            }
            else {
                finished(statusArray: nil, error: nil)
            }
        }
    }
    
    //MARK: - 缓存图片
    class func cacheImage(modelArray: [YSPStatus], finished: (statusArray: [YSPStatus]?, error: NSError?) -> ()) {
        //记录缓存图片的容量大小
        var length = 0
        
        //创建任务组
        let group = dispatch_group_create()
        
        for model in modelArray {
            guard let picURLArray = model.picURLArray else {
                //来到这里说明没有图片要缓存，跳到下一个模型
                continue
            }
            
            //有图片，开始缓存
            //只有一张图片的情况才缓存
            if model.picURLArray?.count == 1 {
                for url in picURLArray {
                    //这是一个异步方法
                    //进入组
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                        //离开组
                        dispatch_group_leave(group)
                        if error != nil {
                            //                        print("缓存图片失败")
                            return
                        }
                        //到了这里说明缓存成功
                        //                    print("缓存图片成功")
                        let data = UIImagePNGRepresentation(image)!
                        length += data.length
                    })
                }
                
            }
        }//模型遍历结束
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //            print("所有图片缓存成功,\(length / 1024)")
            finished(statusArray: modelArray, error: nil)
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
